using System;
using System.Security.Cryptography;
using System.Text;

namespace LiJ.Common.Encrypt
{
	/// <summary>
	/// MD5加密类
	/// </summary>
	public static class Md5
	{
		/// <summary>
		/// 获取16位MD5值
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public static string HalfEncryptHexString(string input)
		{
			string text = EncryptHexString(input);
			if (string.IsNullOrEmpty(text))
			{
				return text;
			}
			return text.Substring(0, 16);
		}

		/// <summary>
		/// 获取MD5加密值
		/// </summary>
		/// <param name="input"></param>
		/// <param name="encoding"></param>
		/// <returns></returns>
		public static string EncryptHexString(string input, Encoding encoding = null)
		{
			if (string.IsNullOrEmpty(input))
			{
				throw new ArgumentNullException("input", "MD5加密的字符串不能为空！");
			}
			if (encoding == null)
			{
				encoding = Encoding.UTF8;
			}
			byte[] array = Encrypt(encoding.GetBytes(input));
			StringBuilder stringBuilder = new StringBuilder(array.Length * 2);
			for (int i = 0; i < array.Length; i++)
			{
				stringBuilder.Append(array[i].ToString("x2"));
			}
			return stringBuilder.ToString();
		}

		/// <summary>
		/// 获取MD5加密值
		/// </summary>
		/// <param name="bytes"></param>
		/// <returns></returns>
		public static byte[] Encrypt(byte[] bytes)
		{
		    if (bytes == null || bytes.Length == 0) throw new ArgumentNullException("bytes", "MD5加密的字节不能为空！");
		    using (var mD = MD5.Create())
		    {
		        return mD.ComputeHash(bytes);
		    }
		}
	}
}
